// pages/goods_detail/index.js
import regeneratorRuntime from '../../lib/runtime/runtime';
import { request } from '../../request/index.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsObj: {},
    //收藏的数据
    collection: [],
    collectionTrue:false
  },
  GoodsInfo: [],
  newcollectionList:[],
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { goods_id } = options
    this.getGoodsDetail(goods_id)
  },
  // 获取详情数据
  async getGoodsDetail(goods_id) {
    const goodsObj = await request({ url: "/goods/detail", data: { goods_id } })
    this.GoodsInfo = goodsObj
    this.setData({
      goodsObj: {
        goods_name: goodsObj.goods_name,
        goods_price: goodsObj.goods_price,
        goods_introduce: goodsObj.goods_introduce,
        pics: goodsObj.pics
      }
    })
  },
  // 点击轮播图放大预览
  handlePrevewImage(e) {
    const Urls = this.GoodsInfo.pics.map(v => v.pics_mid)
    const current = e.currentTarget.dataset.url
    wx.previewImage({
      current,
      urls: Urls,
    });
  },
  // 点击加入购物车
  handelCartAdd() {
    // 获取缓存中的购物车数组
    let cart = wx.getStorageSync("cart") || [];
    // 判断需要添加的商品是否在数组里面
    let index = cart.findIndex(v => v.goods_id === this.GoodsInfo.goods_id)
    if (index === -1) {
      this.GoodsInfo.num = 1
      this.GoodsInfo.checked = true
      cart.push(this.GoodsInfo)
    } else {
      cart[index].num++
    }
    wx.setStorageSync('cart', cart);
    wx.showToast({
      title: '加入成功',
      icon: 'success',
      mask: true,
    });

  },
  // 商品收藏
  collection() {
    // 商品收藏
    const newCollection =wx.getStorageSync("collection")||[]
    newCollection.push(this.GoodsInfo)
    // 点击收藏,将商品详情数据存入本地
    wx.setStorageSync('collection',newCollection);
    wx.showToast({
      title: '商品已成功收藏',
      icon: 'success',
      duration: 2000
    })
    this.setData({collectionTrue:true})
    console.log(this.data.collectionTrue)
  },
})